package ants.map.scent;

import ants.map.Coordinate;

public class ScentMap {

	public static final int NO_SCENT = 1;
	private static final int SCENT_PAGE_COUNT = 2;
	public static final int SOURCE = 20000;
	public static final int SOURCE_DANGER = 6;
	public static final int SOURCE_MINOR = 19000;
	public static final int WATER = 0;

	public static int compare(int scentA, int scentB) {
		return scentA - scentB;
	}

	public static int getStrongestScent(int... scents) {
		int strongest = WATER;
		for (int scent : scents)
			if (0 < compare(scent, strongest))
				strongest = scent;
		return strongest;
	}

	private int currentScentPage;
	private int previousScentPage;
	private final int[][][] scentsFolder;

	public ScentMap(int rows, int cols, int defaultScent) {
		scentsFolder = new int[SCENT_PAGE_COUNT][rows][cols];

		for (int page = 0; page < SCENT_PAGE_COUNT; page++) {
			for (int row = 0; row < rows; row++) {
				for (int col = 0; col < cols; col++) {
					scentsFolder[page][row][col] = defaultScent;
				}
			}
		}

		currentScentPage = 0;
		previousScentPage = getPreviousPage(currentScentPage);
	}

	public void addScent(Coordinate c, int scentDelta) {
		setScent(c, getScent(c) + scentDelta);
	}

	private int getNextPage(int page) {
		int nextPage = page + 1;
		if (nextPage >= SCENT_PAGE_COUNT)
			nextPage -= SCENT_PAGE_COUNT;
		return nextPage;
	}

	private int getPreviousPage(int page) {
		int previousPage = page - 1;
		if (previousPage < 0)
			previousPage += SCENT_PAGE_COUNT;
		return previousPage;
	}

	public int getPreviousScent(Coordinate c) {
		return scentsFolder[previousScentPage][c.row()][c.col()];
	}

	public int getScent(Coordinate c) {
		return scentsFolder[currentScentPage][c.row()][c.col()];
	}

	public void setScent(Coordinate c, int scent) {
		if (scent < 0)
			scent = NO_SCENT;
		scentsFolder[currentScentPage][c.row()][c.col()] = scent;
	}

	public void turnPage() {
		previousScentPage = currentScentPage;
		currentScentPage = getNextPage(currentScentPage);
	}
}
